import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});


// ..............
// 仪表盘数据
// ....................

// 获取用户增长数据
export const getUserGrowthDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 请求用户增长数据的接口
    const response = await apiClient.get('/api/user-growth', {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    // 处理返回的数据
    return {
      success: true,
      data: {
        todayTotal: response.data.todayTotal,  // 今日总用户数
        yesterdayTotal: response.data.yesterdayTotal,  // 昨日总用户数
        growthRate: response.data.growthRate  // 用户增长百分比
      }
    };
  } catch (error) {
    console.error('获取用户增长数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 获取签到增长数据
export const getSigninGrowthDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/signin-growth', {
      headers: { Authorization: `Bearer ${token}` }
    });

    // 明确是签到人数
    return {
      success: true,
      data: {
        todaySignins: response.data.todaySignins,
        yesterdaySignins: response.data.yesterdaySignins,
        growthRate: response.data.growthRate
      }
    };
  } catch (error) {
    console.error('获取签到增长数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 获取学习增长数据
export const getStudyGrowthDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/study-growth', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: {
        todayStudyLogs: response.data.todayStudyLogs,
        yesterdayStudyLogs: response.data.yesterdayStudyLogs,
        growthRate: response.data.growthRate
      }
    };
  } catch (error) {
    console.error('获取学习增长数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 获取新学习与复习数据及增长率
export const getStudyTypeGrowthDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/study-type-growth', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: {
        todayNew: response.data.todayNew,
        todayReview: response.data.todayReview,
        yesterdayNew: response.data.yesterdayNew,
        yesterdayReview: response.data.yesterdayReview,
        newGrowthRate: response.data.newGrowthRate,
        reviewGrowthRate: response.data.reviewGrowthRate
      }
    };
  } catch (error) {
    console.error('获取学习增长数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取失败'
    };
  }
};

// 获取今日与昨日学习时间及增长比率的接口
export const getStudyGrowthTodayVsYesterdayDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/study-growth-today-vs-yesterday', {
      headers: { Authorization: `Bearer ${token}` }
    });

    // 将后端返回的数据转换为前端期望的数据结构
    const data = {
      todayStudyLogs: response.data.todayTotal,
      yesterdayStudyLogs: response.data.yesterdayTotal,
      growthRate: response.data.growthRate, // 保留增长率的字符串格式
      studyDateToday: response.data.studyDateToday,
      studyDateYesterday: response.data.studyDateYesterday
    };

    return {
      success: true,
      data
    };
  } catch (error) {
    console.error('获取学习增长数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};
// 获取错误次数最多的单词及其错误次数总和
export const getErrorWordsStatisticsMostErrorWordsDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/error-words-statistics/most-error-words', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: {
        word: response.data.word,                    // 单词本身
        wordId: response.data.wordId,               // 单词ID
        totalErrorCount: response.data.totalErrorCount  // 错误总次数
      }
    };
  } catch (error) {
    console.error('获取错误单词数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 获取单词总数和例句总数
export const getWordAndSentenceStatsDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/word-and-sentence-stats', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: {
        wordCount: response.data.wordCount,             // 单词总数
        sentenceCount: response.data.sentenceCount      // 例句总数
      }
    };
  } catch (error) {
    console.error('获取单词与例句总数失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 获取最近7天每天的用户签到数
export const getSigninStatsLast_7_DaysDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/signin-stats-last-7-days', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: response.data.data  // 直接返回日期和用户数列表
    };
  } catch (error) {
    console.error('获取签到统计失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 获取错误单词排行榜前五名
export const getTopErrorWordsDataApi = async () => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/api/top-error-words', {
      headers: { Authorization: `Bearer ${token}` }
    });

    return {
      success: true,
      data: response.data.data  // 返回错误单词排行榜数据
    };
  } catch (error) {
    console.error('获取错误单词排行榜失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};





